import zipfile

from django.db.models import F,Q
from django.http import FileResponse, HttpResponse
from django.shortcuts import render
from rest_framework.mixins import CreateModelMixin, ListModelMixin, UpdateModelMixin, DestroyModelMixin, \
    RetrieveModelMixin
from . import models
import time
import os
from oasystem.utils.response import ApiResponse
from rest_framework.viewsets import GenericViewSet, ViewSet, ViewSetMixin, ModelViewSet
from rest_framework.decorators import action
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from .auth import MyJWTAuthentication  # 导入认证类
from . import permiss  # 导入权限类
# Create your views here.
from . import serializers
from .pagenation import PageNumberPaginations, PageNumberMessagePaginations ,PageNumberEvectionPaginations,SalaryPagenation # 导入自己写的分页器
from rest_framework.viewsets import GenericViewSet
from rest_framework.request import Request
import logging

ROLE_LIST = role = [
    {'value': 1, 'label': "超级管理员"},
    {'value': 2, 'label': '管理员'},
    {'value': 3, 'label': '部门经理'},
    {'value': 4, "label": "普通员工"}]


# 生成token的函数
def _get_token(user):
    from rest_framework_jwt.serializers import jwt_payload_handler, jwt_encode_handler
    # 传递用户对象，获取token
    payload = jwt_payload_handler(user)
    token = jwt_encode_handler(payload)
    return token
#拿到redis的连接
def get_redis():
    from oasystem.utils.redis_con import POOL
    import redis
    r = redis.Redis(connection_pool=POOL,decode_responses=True)
    return r
#生成5个验证码
def email_code(count=5):
    import random
    lis = []
    for i in range(count):
        code = random.randint(0, 9)
        lis.append(str(code))
    return ''.join(lis)
'''使用了redis作为验证码缓存的地方'''

class UtilFindPasswordView(GenericAPIView):
    from django.core.cache import cache
    #找回密码功能，不需要进行认证模块
    authentication_classes = []
    #给用户发送验证码的视图函数
    def post(self,request):
        from celery_task import emailtask
        email = request.data.get('email','none')
        username = request.data.get('username')
        try:
            user = models.User.objects.get(**request.data)
            if not user:
                return ApiResponse(code=104,msg='请求失败',data={'error':'邮箱或用户名错误'})
        except:
            return ApiResponse(code=104,msg='请求失败',data={'error':'邮箱或用户名错误'})
        #1 单例模式下生成redis数据库的连接
        redis = get_redis()
        #2 使用django-redis模块,重写cache类实现
        # redis =cache
        #拿到验证码
        code = email_code()
        #1 同步发送邮件
        # send_email(email,code)
        #2 异步发送邮件,函数名.delay(参数)
        emailtask.send_email.delay(recv=email,code=code)
        #将验证码保存到redis数据库中，过期时间是5，EMAILTITLE是key的前缀
        redis.set(settings.EMAILTITLE+username,code,ex=10*60)
        return ApiResponse(msg='验证码发送成功请查收')
    #修改密码的视图函数【暂时注销】
    def put(self,request,*args,**kwargs):
        from django.core.cache import cache
        #1 拿到redis数据库连接，传递序列化类
        redis = get_redis()
        #2 使用django-redis实现redis作为缓存
        # redis = cache
        ser = serializers.FindPasswordSerializer(data=request.data,context={'redis':redis})
        if ser.is_valid():
            return ApiResponse()
        return ApiResponse(code=104,msg='修改密码失败',data=ser.errors,error=ser.errors)


# 用户登录的view
class LoginView(ViewSet):
    # 登录不需要认证
    authentication_classes = []

    # datail=True的时候，查询字符串携带pk
    @action(methods=['POST', ], detail=False)
    def login(self, request, *args, **kwargs):
        username = request.data.get('username')
        password = request.data.get('password')
        try:
            # 用户存在，则一定能拿到用户对象
            user = models.User.objects.get(username=username)
            ret = user.check_password(password)
        except Exception as e:
            return ApiResponse(msg='登录失败', code=104, data={'errors': str(e)})
        # ret = auth.authenticate(request,**request.data)
        if ret:
            role=user.role
            token = _get_token(user)
            user_ser = serializers.CurrentUserSerializer(instance=user)
            if role==1 :
                father = models.EmunFather.objects.filter(Q(role=role)|Q(admin=role)).order_by('create')
            elif  role==2:#老板看到的界面，随意拼接其他人的界面
                father = models.EmunFather.objects.filter(boss=role).order_by('create')
                #部分系统管理的功能老板需要看到，加一些老板独有的功能
            elif role==3:#登录的用户的role=3
                father=models.EmunFather.objects.filter(Q(manager=role)|Q(part__manager_id=user.id)).order_by('create')
            else:
                father = models.EmunFather.objects.filter(role=user.role).order_by('create')
            rightList = []
            for fa in father:
                fa_ser = serializers.EmnuFatherSerializer(instance=fa)
                children = models.EmnuChildren.objects.filter(father=fa)
                children_ser = serializers.EmnuChildrenSerializer(instance=children, many=True)
                dic = dict(fa_ser.data)
                dic.setdefault('children', children_ser.data)
                rightList.append(dic)
            return ApiResponse(msg='登录成功', code=100, role=user.role, id=user.id,
                               token=token,
                               data=user_ser.data,
                               right=rightList,
                               part=user.part_f.name
                               )
        else:
            logging.warning('用户登录失败了')
            logging.error(str(request.user) + '用户登录失败')
            return ApiResponse(msg='用户名或密码错误', code=101)


# 创建单个用户的功能
class CreateUserView(GenericAPIView, CreateModelMixin):
    # 权限限制
    permission_classes = [permiss.SuperAdminPermission]
    queryset = models.User.objects.all()
    serializer_class = serializers.CreateUserSerializer
    # 重写post请求，创建
    def post(self, request):
        ser = serializers.CreateUserSerializer(data=request.data)
        if ser.is_valid():
            return ApiResponse(code=100, data={'username': request.data.get('username')})
        else:

            return ApiResponse(code=500, msg='创建用户失败', error=ser.errors)


# 自己封装的栈
class Stack():
    def __init__(self, lis):
        self.lis = lis

    # 入栈
    def push(self, data):
        self.lis.append(data)

    # 出栈：使用列表分割的方法，拿栈顶到指定位置的数据
    def get_number(self, number):
        result = self.lis[-1:-(number + 1):-1]
        return result

    def get_old_number(self, number):
        result = self.lis[:number]
        return result


# 封装一个固定长度的队列
class Queue():
    def __init__(self, len):
        self.leng = len
        self.lis = []

    def push(self, data):
        lis_len = len(self.lis)
        if lis_len < self.leng:
            self.lis.append(data)
        else:
            self.lis.append(data)
            # 去掉第一个数据。
            self.lis = self.lis[1:]

    # 拿到队列的数据
    def get(self):
        return self.lis

    # 反转
    def get_reverse(self):
        return self.lis[::-1]


# 使用生成器拿读取log文件中的内容
def log_data(filename):
    from logs.logs_path import LOG_DIR
    '''
    :param filename: 要读取的日志文件名
    :param read_type: 读取文件的方向：true是从最后往开头读
                                    false 是从开头往读
    fp.seek(offset,whence):offset是偏移，负值从指针位置往文件前面读，正值从指针位置往后读
                            whence: 0指针在文件开头、1是指针在当前位置、2是指针在文件最后
    :return:
    '''
    fp = open(os.path.join(LOG_DIR, filename), 'rb')
    # size=os.path.getsize(os.path.join(LOG_DIR, filename))
    # if read_type:
    #     #从文件最后往文件开头的方向读内容，
    #     fp.seek(-int(size),2)
    # else:
    #     #从文件开头读取内容
    #     fp.seek(int(size),0)
    for line in fp.readlines():
        try:
            line = str(line.decode())
        # 使用生成器，这样可以节省内存空间。
        except:
            continue
        yield line
    fp.close()

#  使用next来拿到log文件中的内容，其中的get中的max应该是前端传递过来的，
class LogDataView(GenericAPIView, ViewSetMixin):
    # 日志信息
    def get(self, request):
        dat = []
        flag = True
        # 前端传递过来要读取的日志条数
        number = int(request.query_params.get('number'))
        if number > 100 or number < 1:
            return ApiResponse(code=500, msg='失败', error='搜索范围在1-100之间！！')
        # 获取前端传递过来的读取顺序
        order_type = int(request.query_params.get('type'))
        data = log_data('warning.log')
        log_len = 10
        # 自己封装的一个栈
        stack = Stack([])
        queue = Queue(number)
        while flag:
            try:
                line = str(next(data))
                if line.startswith('&&'):
                    y, level, time, module, message = line.split('&&')
                    if level == 'WARNING':
                        dic = {'level': level, 'time': time, 'module': module, 'message': message, 'color': '#d25e32'}
                    else:
                        dic = {'level': level, 'time': time, 'module': module, 'message': message, 'color': '#930808'}
                    # stack.push(dic)
                    queue.push(dic)
                if order_type:
                    # 拿到最新的number条日志
                    dat = queue.get_reverse()
                else:
                    # 拿到最旧的number条日志
                    dat = queue.get()
                log_len = len(dat)
            except StopIteration:
                # 如果生成器读到文件最后，继续next就会报错，捕获后就退出循环
                flag = False
        # 将生成的字典传递给前端进行展示，这个是自己封装的response
        return ApiResponse(data=dat, lenth=log_len)

    # 日志分析，获取饼状图的数据
    def post(self, request):
        # table_type=0 #0是饼状图、1是柱状图、2是折线图
        flag = True
        # 前端传递过来要读取的日志条数
        number = int(request.query_params.get('number'))
        len_number = number
        table_type = int(request.query_params.get('type'))
        if number < 10 or number > 300:
            return ApiResponse(code=500, msg='失败', error='搜索范围在10-300之间！！')
        # 获取前端传递过来的读取顺序
        data = log_data('warning.log')
        warning = 0
        error = 0
        critical = 0
        data_dic = []
        # CRITICAL
        # 给队列传入长度，这样队列的长度就不能超过这个长度了
        queue = Queue(number)
        while flag:
            try:
                line = str(next(data))
                if line.startswith('&&'):
                    # 拿到要处理的数据
                    queue.push(line)
            except StopIteration:
                # 如果生成器读到文件最后，继续next就会报错，捕获后就退出循环
                flag = False
        # 拿到队列中的数据
        line_lis = queue.get()
        for line in line_lis:
            y, level, time, module, message = line.split('&&')
            if level == 'WARNING':
                warning += 1
            elif level == 'ERROR':
                error += 1
            else:
                critical += 1
        all_count = len(line_lis)
        if warning > 0:
            w = '{:.2f}'.format(warning / all_count * 100) + '%'
            data_dic.append({'name': f'WARNING[{warning}]-{w}', 'value': warning})
        if error > 0:
            w = '{:.2f}'.format(error / all_count * 100) + '%'
            data_dic.append({'name': f'ERROR[{error}]-{w}', 'value': error})
        if critical > 0:
            w = '{:.2f}'.format(critical / all_count * 100) + '%'
            data_dic.append({'name': f'CRITICAL[{critical}]-{w}', 'value': critical})
        # 最近200条报警按照月份计算
        return ApiResponse(data=data_dic, lenth=all_count)

    # 日志分析，获取折线图的数据
    def put(self, request):
        import time
        now_year = time.localtime().tm_year  # 获取当前的年份
        the_year = now_year
        now_mount = int(time.localtime().tm_mon)
        mon_lis = []
        warning_div = {}  # {月份:报警数量}
        error_div = {}  # {月份:报警数量}
        # 拿到当前年份的月份列表
        for i in range(1, now_mount + 1):
            mon_lis.append(i)
            warning_div[i] = 0
            error_div[i] = 0
        # 年份数据是给前端的select使用的
        year_lis = [{'label': f'{now_year}年', 'value': int(now_year)}]
        year_obj = models.YearLogData.objects.all()
        year_ser = serializers.YearLogdataViewSerializer(instance=year_obj, many=True)
        for y in year_ser.data:
            year_lis.append({'label': f'{y["year"]}年', 'value': int(y["year"])})
        # 拿到要查看的年份的日志信息
        year = int(request.query_params.get('year'))
        # 获取前端传递过来的读取顺序
        data = log_data('warning.log')
        flag = True
        # CRITICAL
        warn = {
            'data': [],
            'type': 'line',
            # 'stack': 'x',
            'name': "WARNING"
        }
        error = {
            'data': [],
            'type': 'line',
            # 'stack': 'x',
            'name': "ERROR",
        }
        if year == the_year:
            while flag:
                try:
                    line = str(next(data))  # 拿到每行数据
                    if line.startswith('&&'):
                        n, level, time, module, message = line.split('&&')
                        m = time.split('-')[1]
                        if level == 'WARNING':
                            warning_div[int(m)] = warning_div[int(m)] + 1
                        else:
                            error_div[int(m)] = error_div[int(m)] + 1
                except StopIteration:
                    # 如果生成器读到文件最后，继续next就会报错，捕获后就退出循环
                    flag = False
            for v in warning_div.values():
                warn['data'].append(v)
            for v in error_div.values():
                error['data'].append(v)
            datas = [warn, error]
            mon_lis = [f'{i}月' for i in mon_lis]
            return ApiResponse(data=datas, year=year_lis, mon_lis=mon_lis)
        else:
            year_obj = models.YearLogData.objects.filter(year=str(year)).first()
            if year_obj:
                mon_data = models.DetalLogdata.objects.filter(year=year_obj).order_by('order')
                ser = serializers.DeatailLogDataViewSerialize(instance=mon_data, many=True)
                mount_set = []
                for div in ser.data:
                    if div['type'] == 'WARNING':
                        warn['data'].append(div['count'])
                        mount_set.append(div['mount'])
                    else:
                        error['data'].append(div['count'])
                datas = [warn, error]
                return ApiResponse(data=datas, mon_lis=list(mount_set), year=year_lis)
            return ApiResponse(code=404, data='没有相应的数据', year=year_lis)

    # 日志分析，获取柱状图的数据
    def patch(self, request):
        import time
        now_year = time.localtime().tm_year  # 获取当前的年份
        the_year = now_year
        now_mount = int(time.localtime().tm_mon)
        mon_lis = []
        warning_div = {}  # {月份:报警数量}
        error_div = {}  # {月份:报警数量}
        # 拿到当前年份的月份列表
        for i in range(1, now_mount + 1):
            mon_lis.append(i)
            warning_div[i] = 0
            error_div[i] = 0
        # 年份数据是给前端的select使用的
        year_lis = [{'label': f'{now_year}年', 'value': now_year}]
        # for i in range(4):
        #     now_year -= 1
        #     year_lis.append({'label': f'{now_year}年', 'value': now_year})
        year_obj = models.YearLogData.objects.all()
        year_ser = serializers.YearLogdataViewSerializer(instance=year_obj, many=True)
        for y in year_ser.data:
            year_lis.append({'label': f'{y["year"]}年', 'value': int(y["year"])})
        # 拿到要查看的年份的日志信息
        year = int(request.query_params.get('year'))
        # 获取前端传递过来的读取顺序
        data = log_data('warning.log')
        flag = True
        # CRITICAL
        warn = {
            'data': [],
            'type': 'bar',
            # 'stack': 'x',
            'name': "WARNING"
        }
        error = {
            'data': [],
            'type': 'bar',
            # 'stack': 'x',
            'name': "ERROR",
        }
        if year == the_year:
            while flag:
                try:
                    line = str(next(data))  # 拿到每行数据
                    if line.startswith('&&'):
                        n, level, time, module, message = line.split('&&')
                        m = time.split('-')[1]
                        if level == 'WARNING':
                            warning_div[int(m)] = warning_div[int(m)] + 1
                        else:
                            error_div[int(m)] = error_div[int(m)] + 1
                except StopIteration:
                    # 如果生成器读到文件最后，继续next就会报错，捕获后就退出循环
                    flag = False
            for v in warning_div.values():
                warn['data'].append(v)
            for v in error_div.values():
                error['data'].append(v)
            datas = [warn, error]
            mon_lis = [f'{i}月' for i in mon_lis]
            return ApiResponse(data=datas, year=year_lis, mon_lis=mon_lis)
        else:
            year_obj = models.YearLogData.objects.filter(year=str(year)).first()
            if year_obj:
                mon_data = models.DetalLogdata.objects.filter(year=year_obj).order_by('order')
                ser = serializers.DeatailLogDataViewSerialize(instance=mon_data, many=True)
                mount_set = []
                for div in ser.data:
                    if div['type'] == 'WARNING':
                        warn['data'].append(div['count'])
                        mount_set.append(div['mount'])
                    else:
                        error['data'].append(div['count'])
                datas = [warn, error]
                return ApiResponse(data=datas, mon_lis=list(mount_set), year=year_lis)
            return ApiResponse(code=404, data='没有相应的数据', year=year_lis)


# 管理员更新用户信息
class UpdateUserView(GenericViewSet, DestroyModelMixin, UpdateModelMixin):
    queryset = models.User.objects
    serializer_class = serializers.UpdateUserView
    permission_classes = [permiss.SuperAdminPermission]

    # 更新用户信息
    def update(self, request, *args, **kwargs):
        id = kwargs.get('pk')
        role = request.data.get('role')
        part = models.Part.objects.get(id=request.data.get('part_f'))
        position = models.Position.objects.get(id=request.data.get('position'))
        desc = position.name  # 用户的描述信息
        if role == 3:  # 更新权限是经理，职位也是经理
            if '经理' in position.name:
                user = models.User.objects.filter(part=part, role=3).last()
                if user:  # 该部门已经存在经理了。
                    if int(id) == user.id:  # 当前修改的人就是经理，则可以修改
                        models.User.objects.filter(id=id).update(desc=desc, **request.data)
                        return ApiResponse(code=100)
                    else:
                        return ApiResponse(code=500, error='该部门已经存在经理了！！')
                else:  # 该部门没有经理，直接更新
                    models.User.objects.filter(id=id).update(desc=desc, **request.data)
                    # 部门经理改变了，part表中的经理字段外键也要修改
                    models.Part.objects.filter(id=part.id).update(manager_id=id)
                    return ApiResponse(code=100)
            else:
                return ApiResponse(code=500, error='权限是经理，职位必须是部门经理！！')
        elif role in [1, 2]:
            if part.name == '老板部':
                # 权限是超级管理有员或管理员，所在部门必须是老板部
                models.User.objects.filter(id=id).update(desc=desc, **request.data)
                return ApiResponse(code=100)
            return ApiResponse(code=500, error='权限是管理员，必须属于老板部')
        elif role == 4:
            if '经理' in position.name or part.name == '老板部':
                return ApiResponse(code=500, error='权限与职业不匹配！！')
            models.User.objects.filter(id=id).update(desc=desc, **request.data)
            return ApiResponse(code=100)
        else:
            return ApiResponse(code=500, error='携带的权限不存在')

    # 删除单个用户
    def destroy(self, request, *args, **kwargs):
        id = kwargs.get('pk')
        if id:
            try:
                user = models.User.objects.get(id=id, is_active=True)
                name = user.name
                if user:
                    user.is_active = False
                    user.is_show = False
                    user.save()
                    return ApiResponse(code=100, name=name)
                return ApiResponse(code=404, msg='正在删除不存在的用户')
            except Exception as e:
                return ApiResponse(code=500, msg='删除失败')
        return ApiResponse(code=404, msg='正在删除不存在的用户')


# 用户修改密码
class EditPasswordView(GenericViewSet, UpdateModelMixin):
    queryset = models.User.objects
    serializer_class = serializers.EditPasswordViewSeriazer

    @action(methods=['patch'], detail=False)
    def password(self, request):
        ser = serializers.EditPasswordViewSeriazer(data=request.data, context={'request': request})
        if ser.is_valid():
            return ApiResponse(code=100, msg='修改密码成功')
        else:
            return ApiResponse(code=500, msg=str(ser.errors))
#拿到实习转正需要的部门和职位的关系库
class PartForPositive(GenericViewSet,ListModelMixin):
    def list(self, request, *args, **kwargs):
        part = request.query_params.get('id')
        position = models.Position.objects.filter(Q(part_id=part)&~Q(name__contains='实习生'))
        ser = serializers.PartForPositiveSerializer(instance=position,many=True)

        return ApiResponse(code=100,data=ser.data)
class PositiveView(GenericViewSet,ListModelMixin,UpdateModelMixin):
    pagination_class = PageNumberEvectionPaginations
    serializer_class = serializers.PositiveSerializer
    def list(self, request, *args, **kwargs):
        queryset = models.User.objects.filter(desc__contains='实习生').order_by('id')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)
    def update(self, request, *args, **kwargs):
        try:
            user = models.User.objects.get(id=request.data.get('id'))
            position = models.Position.objects.get(id=request.data.get('position'))

            user.position=position
            user.desc=position.name#更改用户描述
            user.save()
            return ApiResponse()
        except Exception as e:
            print(e)

            return ApiResponse(code=500,error='无此数据，无法操作')
#会议室创建
class ConferenceView(GenericViewSet,ListModelMixin,CreateModelMixin,DestroyModelMixin,UpdateModelMixin):
    serializer_class = serializers.ConferenceViewSerializer
    queryset = models.Conference.objects
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        queryset = self.queryset.filter(is_delete=False).order_by('id')
        type=request.query_params.get('type')
        page = self.paginate_queryset(queryset)
        if type=='1':
            serializer = self.get_serializer(queryset, many=True)
            return ApiResponse(data=serializer.data)
        else:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
    def create(self, request, *args, **kwargs):
        ser = self.serializer_class(data=request.data)
        if ser.is_valid():
            return ApiResponse()
        return ApiResponse(code=500,error=ser.errors)
    def destroy(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        try:
            models.Conference.objects.filter(id=id).update(is_delete=True)
        except Exception as  e:
            return ApiResponse(code=500,error=str(e))
        return ApiResponse()
    def update(self, request, *args, **kwargs):
        id = request.data.pop('id')
        try:
             self.queryset.filter(id=id).update(**request.data)
             return ApiResponse(code=100)
        except:
            return ApiResponse(code=500,error='无此数据，无法修改')


class ApplyConferenceView(GenericViewSet,ListModelMixin,CreateModelMixin,DestroyModelMixin):
    serializer_class = serializers.ShowApplyConferenceserializer
    queryset = models.ApllyConference.objects
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        type= request.query_params.get('type')
        start=request.query_params.get('start')
        end = request.query_params.get('end')
        if type=='1':
            #搜索某一时间段上会议室占用情况,搜索所有
            queryset=models.ApllyConference.objects.filter(Q(start__lte=end,end__gte=end)|Q(start__lte=start,end__gt=start)|Q(start__lte=start,end__gte=end)&Q(is_delete=False)).order_by('id')
        elif type=='2':
            #我的会议申请
            condition = request.query_params.get('condition')
            queryset = models.ApllyConference.objects.filter(position=condition,is_delete=False,applier_id=request.auth.get('id'))
        else:
            queryset = models.ApllyConference.objects.filter(is_delete=False).order_by('id')

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)

    def create(self, request, *args, **kwargs):
        ser = serializers.ApplyConferenceViewSerializer(data=request.data,context={'applier':request.auth.get('id')})
        if ser.is_valid():
           return ApiResponse()
        return ApiResponse(code=500,error=str(ser.errors.get('non_field_errors','操作失败')))
    def destroy(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        try:
            con=models.ApllyConference.objects.get(id=id)
            con.is_delete=True
            con.save()
        except:
            return ApiResponse(code=500)
        return ApiResponse(msg='destroy')

# 可选择的选项
class UtilView(ViewSet):
    # 创建用户需要的：职位、部门、性别、角色
    @action(methods=['get'], detail=False)
    def userchoice(self, request):
        position = models.Position.objects.all()
        part = models.Part.objects.filter(is_delete=False)
        ser = serializers.PositionReadSerializer(instance=position, many=True)
        ser_part = serializers.PartSerializer(instance=part, many=True)
        role = [
            {'id': 1, 'name': "超级管理员"},
            {'id': 2, 'name': '管理员'},
            {'id': 3, 'name': '部门经理'},
            {'id': 4, "name": "普通员工"}]
        part_position = []
        manager_id = []  # 管理员id
        staff_id = []  # 普通用户id
        booss_id = []  # 老板部门职员的id
        for po in ser.data:
            if '经理' in po['label']:
                manager_id.append(po['value'])
            elif '员工' in po['label'] :
                staff_id.append(po['value'])
            elif '老板' in po['label'] or '管理员' in po['label']:
                booss_id.append(po['value'])

        for part in ser_part.data:
            div = {}
            div['value'] = part['value']
            div['label'] = part['label']
            div['children'] = []
            for po in ser.data:
                if po.get('partname') in part.get('label'):
                    div['children'].append(po)
            part_position.append(div)

        return ApiResponse(username=request.user,
                           data={'part_position': part_position, "role": role, 'boss_id': booss_id,
                                 'staff_id': staff_id, 'manager_id': manager_id})


class ShowUserView(GenericViewSet, ListModelMixin):
    authentication_classes = []
    queryset = models.User.objects.filter(is_active=True, is_show=True).order_by('-date_joined')  # 这个在这里可写可不写，因为不会用到
    serializer_class = serializers.ShowUserSerializer  # 学生的序列化器
    pagination_class = PageNumberPaginations  # 使用重写的分页器


# 获取登录用户的信息，展示出来了
class CurrentUserView(ViewSet):
    @action(methods=['get'], detail=False)
    def currentuser(self, request):
        user = models.User.objects.get(id=request.auth.get('id'))
        ser = serializers.CurrentUserSerializer(instance=user)
        father = models.EmunFather.objects.filter(role=user.role)
        rightList = []
        for fa in father:
            fa_ser = serializers.EmnuFatherSerializer(instance=fa)
            children = models.EmnuChildren.objects.filter(father=fa)
            children_ser = serializers.EmnuChildrenSerializer(instance=children, many=True)
            dic = dict(fa_ser.data)
            dic.setdefault('children', children_ser.data)
            rightList.append(dic)
        return ApiResponse(data=ser.data, right=rightList)


# 管理员创建部门，查看部门信息
# 需要管理员权限，才能创建
class AdminCreateView(ViewSet, GenericAPIView):
    permission_classes = [permiss.SuperAdminPermission]
    # 创建部门的方法
    @action(methods=['post'], detail=False)
    def createpart(self, request):
        ser = serializers.ShowPartViewSerializer(data=request.data)
        if ser.is_valid():
            return ApiResponse(code=100, msg=f'创建{request.data.get("name", "")}成功', data=ser.data)
        else:
            return ApiResponse(code=500, msg='创建部门失败', error=ser.errors)


# 获取用来展示的信息：
class ShowPartView(GenericViewSet, ListModelMixin):
    # 用来展示部门信息的，所有用户都可以查看
    queryset = models.Part.objects.filter(is_delete=False)
    serializer_class = serializers.ShowPartViewSerializer
    pagination_class = PageNumberPaginations


# 展示职位信息,查看和创建职位
class PositionView(GenericViewSet, ListModelMixin, CreateModelMixin):
    serializer_class = serializers.PositionViewSerializer
    queryset = models.Position.objects.all().order_by('-create_time')
    pagination_class = PageNumberPaginations

    def create(self, request, *args, **kwargs):
        ser = serializers.PositionViewSerializer(data=request.data)
        if ser.is_valid():
            return ApiResponse(code=100, msg='创建职位成功')
        else:
            return ApiResponse(code=500, error=str(ser.errors.get('non_field_errors')[0]))


# 部门管理/创建职位 需要的部门信息
class PartForPositionView(GenericViewSet, ListModelMixin):
    queryset = models.Part.objects.filter(is_delete=False)
    serializer_class = serializers.PartForPositionViewSerializer
    # 重写list方法，修改返回格式
    def list(self, request, *args, **kwargs):
        reim = request.query_params.get('type')#type=reim时就是要财务和老板两个部门
        if reim=='reim':
            queryset=models.Part.objects.filter(Q(name__contains='财务部')|Q(name__contains='老板部'))
        else:
            queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(code=100, data=serializer.data)


# 用户管理/用户信息：表格展示用户信息
class UserMessageView(GenericViewSet, ListModelMixin):
    pagination_class = PageNumberPaginations
    serializer_class = serializers.ShowUserSerializer

    def list(self, request, *args, **kwargs):
        part = request.query_params.get('part')
        if part != '':
            queryset = models.User.objects.filter(part_f_id=part, is_active=True, is_show=True).order_by('-change')

        else:
            queryset = models.User.objects.filter(is_active=True, is_show=True).order_by('-change')
        # 上面的是重写的部分，用来获取指定的数据和一些简单逻辑判断
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(code=100, data=serializer.data, role_list=ROLE_LIST)


# 个人中心查看用户信息、
class PersonCenterView(GenericViewSet, RetrieveModelMixin):
    queryset = models.User.objects
    serializer_class = serializers.PersonCenterViewSerializer


# 个人中心更新头像的功能
class PersonCenterUpdateview(GenericAPIView, ViewSetMixin):
    # 个人中心修改信息，不包括头像
    def post(self, request):
        ser = serializers.PersonCenterViewSerializer(data=request.data, context={'id': request.auth.get('id')})
        if ser.is_valid():
            return ApiResponse(code=100)
        return ApiResponse(code=500, error=ser.errors)
    # 个人中心修改头像
    def patch(self, request):
        ser = serializers.PersonIconViewSerializer(data=request.data,
                                                   context={'id': request.auth.get('id'), 'request': request})
        if ser.is_valid():
            return ApiResponse(code=100)
        return ApiResponse(code=500, error=ser.errors)
    # 头像修改后，需要将前端缓存在vuex中的头像重新获取
    def get(self, request):
        user = models.User.objects.get(id=request.auth.get('id'))
        ser = serializers.PersonIconViewSerializer(instance=user)
        return ApiResponse(code=100, data=ser.data)


# 管理员创建公司通知
class AdminCompanyMessage(GenericAPIView, ListModelMixin, CreateModelMixin, DestroyModelMixin):
    queryset = models.CompanyMessage.objects.filter(is_show=True).order_by('-created')
    serializer_class = serializers.CompanyMessageSerializer
    pagination_class = PageNumberMessagePaginations

    def get(self, request):
        return self.list(request)

    def post(self, request):
        try:
            self.create(request)
            return ApiResponse(code=100, msg='创建成功')
        except:
            return ApiResponse(code=500, msg='创建失败')

    def delete(self, request):
        id = request.query_params.get('pk')
        try:
            models.CompanyMessage.objects.filter(id=id).update(is_show=False)
            return ApiResponse()
        except:
            return ApiResponse(code=500)

    def patch(self, request):
        id = request.query_params.get('id')
        try:
            models.CompanyMessage.objects.filter(id=id).update(**request.data)
            return ApiResponse()
        except:
            return ApiResponse(code=500)

    def put(self, request):
        obj = models.CompanyMessage.objects.filter(is_show=True).order_by('-created')[0]
        ser = serializers.CompanyMessageSerializer(instance=obj)
        return ApiResponse(data=ser.data)


# 部门通知管理
class PartMessageView(GenericAPIView, ListModelMixin, CreateModelMixin, UpdateModelMixin):
    queryset = models.PartMessage.objects.filter(is_show=True).order_by('-created')
    serializer_class = serializers.PartMessageViewSerializer
    pagination_class = PageNumberMessagePaginations

    def get(self, request):
        return self.list(request)

    def post(self, request):
        try:
            part = request.data.pop('part')
            models.PartMessage.objects.create(**request.data, part_id=part)
            return ApiResponse(code=100, msg='创建成功')
        except:
            return ApiResponse(code=500, msg='创建失败')

    def delete(self, request):
        id = request.query_params.get('pk')
        try:
            models.PartMessage.objects.filter(id=id).update(is_show=False)
            return ApiResponse()
        except:
            return ApiResponse(code=500)

    def put(self, request):
        type = request.query_params.get('type')
        user = models.User.objects.get(username=request.user)
        part = models.PartMessage.objects.filter(part=user.part_f, is_show=True).order_by('-created')
        if not int(type):
            ser = serializers.PartMessageViewSerializer(instance=part[0])
        else:
            ser = serializers.PartMessageViewSerializer(instance=part, many=True)
        return ApiResponse(data=ser.data)

    def patch(self, request):
        id = request.query_params.get('id')
        try:
            models.PartMessage.objects.filter(id=id).update(**request.data)
            return ApiResponse()
        except:
            return ApiResponse(code=500)


class StaffMessageView(GenericViewSet, ListModelMixin):
    queryset = models.PartMessage.objects.filter(is_show=True)
    serializer_class = serializers.PartMessageViewSerializer
    pagination_class = PageNumberMessagePaginations

    def list(self, request, *args, **kwargs):
        user = models.User.objects.get(username=request.user)
        part = user.part_f
        queryset = models.PartMessage.objects.filter(part=part, is_show=True).order_by('-created')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)


# 公司文件
class CompanyFileView(GenericAPIView, ListModelMixin, DestroyModelMixin, CreateModelMixin):
    queryset = models.CompanyFile.objects.filter(is_show=True)
    serializer_class = serializers.CompanyFileSerializer
    pagination_class = PageNumberMessagePaginations

    def get(self, request, *args, **kwargs):
        return self.list(request)

    def delete(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        try:
            models.CompanyFile.objects.filter(id=id).update(is_show=False)
        except:
            return ApiResponse(code=500, msg='失败')
        return ApiResponse(code=100)

    def post(self, request, *args, **kwargs):
        filename = str(request.data.get('filename')).split('.')[-1]
        if filename not in ['pdf','PDF']:
            return ApiResponse(code=300,msg='请传pdf格式的数据')
        try:
            desc = request.data.get('desc')
            name = request.data.get('name')
            models.CompanyFile.objects.create(desc=desc, name=name, filename=request.FILES.get('filename'),
                                              upload_id=request.auth.get('id'))
        except:
            return ApiResponse(code=500, msg='创建失败')
        return ApiResponse()


from django.conf import settings

#下载文件
class DownloadFileView(GenericAPIView):
    def get(self, request):
        file_id = request.query_params.get('id')
        file_obj = models.CompanyFile.objects.filter(id=file_id).first()
        if file_obj:
            # 拿到文件在数据库中存储的位置
            media_file = str(file_obj.filename)
            # 拼接文件路径
            filepath = os.path.join(settings.MEDIA_ROOT, media_file)
            # 拿到文件的名字（该名字包含了文件的格式）
            filename = media_file.split(r'/')[-1]
            file = open(filepath, 'rb')
            response = FileResponse(file)  # 生成文件对象application/msword  application/octet-stream
            response['Content-Type'] = 'application/octet-stream'
            # name.split('.')[0] + '.docx'，
            name = filename
            response['Content-Disposition'] = 'attachment;filename ="%s"' % (
                name.encode('utf-8').decode('ISO-8859-1'))
            return response


from pydocx import PyDocX

#获取文件的id，返回文件的可访问地址。
class PdfUrlView(GenericAPIView):
    def get(self, request):
        file_id = request.query_params.get('id')
        file_path=models.CompanyFile.objects.get(id=file_id)
        file = str(file_path.filename)
        path_file = os.path.join(settings.URL,'media', file)
        return ApiResponse(url=path_file)


#出差申请功能
class CreateEvectionView(GenericViewSet, ListModelMixin, CreateModelMixin,DestroyModelMixin):
    queryset = models.Evection.objects
    serializer_class = serializers.CreateEvectionView
    pagination_class = PageNumberEvectionPaginations
    def create(self, request, *args, **kwargs):
        try:
            super().create(request,*args, **kwargs)
            return ApiResponse(code=100)
        except Exception as e:
            print(str(e))
            return ApiResponse(code=500)
    def list(self, request, *args, **kwargs):
        #是0的时候，返回的是所有未审核的申请给用户看，展示到创建申请的页面
        is_create = request.query_params.get('create')
        user_id = request.auth.get('id')
        if int(is_create):
            #用户要查看的出差申请数据（1是未审核，2是审核通过，3是审核不通过）
            condition =int(request.query_params.get('condition'))
            if condition in [1,2,3]:
                queryset = models.Evection.objects.filter(condition=condition,is_delete=False,apllier_id=user_id).order_by('-create_time')
            else:
                queryset = models.Evection.objects.filter(is_delete=False,apllier_id=user_id).order_by('-create_time')
        else:#拿到所有未审核的申请，给用户看，让用户知道自己的申请已经写好了
            queryset = models.Evection.objects.filter(is_delete=False, apllier_id=user_id,condition=1).order_by('-create_time')

        # queryset = models.Evection.objects.filter(is_delete=False)
        page = self.paginate_queryset(queryset)
        if page is not None:
            #是否使用分页，修改分页是的序列化器
            serializer = serializers.ShowEvectionSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = serializers.ShowEvectionSerializer(queryset, many=True)
        return ApiResponse(data=serializer.data)

    def destroy(self, request, *args, **kwargs):
        id =int( request.query_params.get('id'))
        try:
            models.Evection.objects.filter(id=id,apllier__username=request.user).update(is_delete=True)
            return ApiResponse(code=100)
        except Exception as e:
            return ApiResponse(code=500,error=str(e))
#员工管理加班申请
class ManageEvectionView(GenericViewSet,ListModelMixin,UpdateModelMixin):
    serializer_class = serializers.ManageEvectionViewSerializer
    queryset = models.Evection.objects.filter(is_delete=False)
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        #拿到要查看的不同审核情况的申请
        condition = request.query_params.get('condition')
        queryset =models.Evection.objects.filter(is_delete=False,checker__manager_id=request.auth.get('id'),condition=condition).order_by('-create_time')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(data=serializer.data,code=100)
    def update(self, request, *args, **kwargs):
        try:
            id = request.query_params.get('id')
            type = int(request.query_params.get('type'))
            evection = models.Evection.objects.get(id=id)
        except:
            return ApiResponse(code=404,error='无此数据')
        if type:
            #审核不通过、condition改成3，将原因写入
            evection.condition=3
            evection.result=request.data.get('result')
            evection.save()
            return ApiResponse(code=100)
        else:
            #审核通过
            evection.condition=2
            evection.save()
            return ApiResponse(code=100)
#员工加班
class ExtraWorkView(GenericViewSet,ListModelMixin,UpdateModelMixin,CreateModelMixin,DestroyModelMixin):
    queryset = models.ExtraWork.objects.filter(condition=1)
    serializer_class = serializers.ExtraWorkViewListSerializer
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        type = request.query_params.get('type')
        if type=='1':#未审核
            queryset = models.ExtraWork.objects.filter(condition=1,applier_id=request.auth.get('id'),is_delete=False)
        elif type=='2':#审核通过
            queryset = models.ExtraWork.objects.filter(condition=2, applier_id=request.auth.get('id'), is_delete=False)
        elif type=='3':#审核不通过
            queryset = models.ExtraWork.objects.filter(condition=3, applier_id=request.auth.get('id'), is_delete=False)
        else:
            queryset = models.ExtraWork.objects.filter(condition=1, applier_id=request.auth.get('id'), is_delete=False)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)
    def create(self, request, *args, **kwargs):
        ser = serializers.ExtraWorkViewSerializer(data=request.data,context={'id':request.auth.get('id')})
        if ser.is_valid():
            return ApiResponse(code=100)
        else:
            return ApiResponse(code=500,error=ser.errors)
    def update(self, request, *args, **kwargs):
        return ApiResponse()
    def destroy(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        try:
            extra=models.ExtraWork.objects.get(id=id)
            if extra.condition==2:
                return ApiResponse(code=500,error='无法删除此数据，已经审核成功了。')
            extra.is_delete=True
            extra.save()
            return ApiResponse()
        except:
            return ApiResponse(code=500,error='删除失败')

#部门经理审核加班
class ManageExtraWorkView(GenericViewSet,ListModelMixin,UpdateModelMixin):
    serializer_class = serializers.ManageExtraWorkViewSerializer
    queryset = models.ExtraWork.objects.filter(is_delete=False)
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        #拿到要查看的不同审核情况的申请
        condition = request.query_params.get('condition')
        queryset =models.ExtraWork.objects.filter(is_delete=False,checker__manager_id=request.auth.get('id'),condition=int(condition)).order_by('-id')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(data=serializer.data,code=100)
    def update(self, request, *args, **kwargs):
        try:
            id = int(request.query_params.get('id'))
            is_pass = int(request.query_params.get('type'))
            evection = models.ExtraWork.objects.get(id=id)
        except:
            return ApiResponse(code=404,error='无此数据')
        if is_pass==1:
            #申请不通过、condition改成3，将原因写入
            evection.condition=3
            evection.result=request.data.get('result')
            evection.save()
            return ApiResponse(code=100)
        else:
            #申请通过时的操作
            evection.condition=2
            evection.save()
            return ApiResponse(code=100)
#创建车辆信息。
class CreateCarView(GenericViewSet,ListModelMixin,CreateModelMixin,UpdateModelMixin,DestroyModelMixin):
    queryset = models.Car.objects
    serializer_class = serializers.CreateCarViewSerializer
    pagination_class = PageNumberPaginations
    def list(self, request, *args, **kwargs):
        queryset =self.queryset.filter(is_delete=False).order_by('id')
        is_type = request.query_params.get('type')
        if is_type=='page':
            page = self.paginate_queryset(queryset)
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        else:
            serializer = serializers.CarForApplyCar(instance=queryset,many=True)
            return ApiResponse(data=serializer.data)
    def create(self, request, *args, **kwargs):
        super().create(request,*args,**kwargs)
        return ApiResponse(code=100)
    def update(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        try:
            self.queryset.filter(id=id).update(**request.data)
            return ApiResponse(code=100, id=id)
        except :
            return ApiResponse(code=500,msg='修改失败')
    def destroy(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        try:
            self.queryset.filter(id=id).update(is_delete=True)
            return ApiResponse(code=100)
        except Exception as e:
            return ApiResponse(code=100,error=str(e))

#员工申请用车
class ApplyCarView(GenericViewSet,ListModelMixin,DestroyModelMixin,CreateModelMixin,UpdateModelMixin):
    queryset = models.ApplyCar.objects
    serializer_class = serializers.ApplyCarViewSerializer
    pagination_class = PageNumberMessagePaginations
    def list(self, request, *args, **kwargs):
        condition = request.query_params.get('condition')
        who = request.query_params.get('type')
        if who=='manager':#管理获取用户申请
            queryset = models.ApplyCar.objects.filter(is_delete=False, checker__manager_id=request.auth.get('id'), condition=condition).order_by('-id')
        else:
            queryset = models.ApplyCar.objects.filter(is_delete=False,applier_id=request.auth.get('id'),condition=condition).order_by('-id')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = serializers.ShowApplyCarViewSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = serializers.ShowApplyCarViewSerializer(queryset, many=True)
        return ApiResponse(data=serializer.data)

    def destroy(self, request, *args, **kwargs):
        id=request.query_params.get('id')
        try:
            app=models.ApplyCar.objects.get(id=id,is_delete=False)
            if app:
                app.is_delete=True
                app.save()
                return ApiResponse(code=100)
            return ApiResponse(code=500,error='无此数据，无法删除')
        except Exception as e:
            return ApiResponse(code=500,error=str(e))

    def create(self, request, *args, **kwargs):
        request.data['applier']=request.auth.get('id')
        ser = serializers.ApplyCarViewSerializer(data=request.data)
        if ser.is_valid():
            return ApiResponse(code=100)
        return ApiResponse(code=500,error=str(ser.errors.get('non_field_errors')))

    def update(self, request, *args, **kwargs):
        is_pass = request.query_params.get('type')
        id = request.query_params.get('id')
        if is_pass=='0':
            try:
                app=self.queryset.get(id=id)
                app.condition=2#审核通过
                app.save()
            except Exception as  e:
                return ApiResponse(code=500,error='无此数据，无法删除')
        else:
            try:
                self.queryset.filter(id=id).update(result=request.data.get('result'),condition=3)
            except Exception as  e:
                return ApiResponse(code=500, error='无此数据，无法删除')
        return ApiResponse(code=100)

#报销审核
class ApplyReimView(GenericViewSet,ListModelMixin,CreateModelMixin,DestroyModelMixin,UpdateModelMixin):
    queryset = models.Reim.objects
    serializer_class = serializers.ApplyReimViewSerializer
    pagination_class = PageNumberEvectionPaginations
    def create(self, request, *args, **kwargs):
        try:
            float(request.data.get('cost'))
        except:
            return ApiResponse(code=500,error='报销金额不是数值')
        ser = serializers.ApplyReimViewSerializer(data=request.data,context={'request':request})
        if ser.is_valid():
            return ApiResponse()
        return ApiResponse(code=500,error='未知错误')
    def list(self, request, *args, **kwargs):
        who = request.query_params.get('type')
        condition = request.query_params.get('condition')
        if who=='1':#申请人查看报销情况
            queryset = self.queryset.filter(applier_id=request.auth.get('id'),is_delete=False,condition=condition).order_by('-id')
        else:#报销审核人查看情况
            queryset = self.queryset.filter(part__manager_id=request.auth.get('id'),is_delete=False,condition=condition).order_by('-id')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer =serializers.ShowApplyReimViewSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)
    def destroy(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        try:
            reim=self.queryset.get(id=id)
            reim.is_delete=True
            reim.save()
            return ApiResponse(code=100)
        except:
            return ApiResponse(code=500,error='无此数据，无法删除')
    def update(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        type = request.query_params.get('type')
        try:
            reim = self.queryset.get(id=id)
        except:
            return ApiResponse(code=500,error='无此数据')
        if type=='1':
            #不通过
            reim.condition=3
            reim.result = request.data.get('result')
        else:
            reim.condition=2
        reim.save()
        return ApiResponse(code=100)
#录入档案文件
class ManageRecordView(GenericViewSet,CreateModelMixin,ListModelMixin,DestroyModelMixin):
    queryset = models.Record.objects
    serializer_class = serializers.ShowRecordSerializer
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        queryset = models.Record.objects.filter(is_delete=False).order_by('-id')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)
    def create(self, request, *args, **kwargs):
        username = request.data.get('staff')
        try:
            user= models.User.objects.get(username=username)
            request.data['staff']=user.id
            request.data['part']=user.part_f.id
            ser =serializers.ManageRecordViewSerializer(data=request.data)
            if ser.is_valid():
                return ApiResponse(code=100)
            else:
                return ApiResponse(code=500,error='该员工的档案已经录入，无法再录入')
        except:
            return ApiResponse(code=500,error='无此员工，无法录入。')
    def destroy(self, request, *args, **kwargs):
        id= request.query_params.get('id')
        try:
            models.Record.objects.filter(id=id).update(is_delete=True)
        except:
            return ApiResponse(code=500,error='没有此档案，无法删除')
        return ApiResponse(code=100)

#下载档案文件
class DownloadRecordFileView(GenericAPIView):
    def get(self,request):
        file_id = request.query_params.get('id')
        file_obj = models.Record.objects.filter(id=file_id).first()
        if file_obj:
            # 拿到文件在数据库中存储的位置
            media_file = str(file_obj.file)
            # 拼接文件路径
            filepath = os.path.join(settings.MEDIA_ROOT, media_file)
            # 拿到文件的名字（该名字包含了文件的格式）
            filename = media_file.split(r'/')[-1]
            file = open(filepath, 'rb')
            response = FileResponse(file)  # 生成文件对象application/msword  application/octet-stream
            response['Content-Type'] = 'application/octet-stream'
            # name.split('.')[0] + '.docx'，
            name = filename
            response['Content-Disposition'] = 'attachment;filename ="%s"' % (
                name.encode('utf-8').decode('ISO-8859-1'))
            return response
        return ApiResponse(code=500,msg='get')

class ManageConstractView(GenericViewSet,ListModelMixin,CreateModelMixin,DestroyModelMixin):
    queryset = models.Contract.objects
    serializer_class = serializers.ShowConstractSerializer
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        queryset = models.Contract.objects.filter(is_delete=False).order_by()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)

    def create(self, request, *args, **kwargs):
        username = request.data.get('staff')
        try:
            user = models.User.objects.get(username=username)
            request.data['staff'] = user.id
            request.data['part'] = user.part_f.id
            ser = serializers.ManageConstractViewSerializer(data=request.data)
            if ser.is_valid():
                return ApiResponse(code=100)
            return ApiResponse(code=500, error='该员工的合同已经录入，无法再录入')
        except:
            return ApiResponse(code=500, error='无此员工，无法录入。')

    def destroy(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        try:
            models.Contract.objects.filter(id=id).update(is_delete=True)
        except:
            return ApiResponse(code=500, error='没有此合同，无法删除')
        return ApiResponse(code=100)
#下载合同文件
class DownloadConstractFileView(GenericAPIView):
    def get(self,request):
        file_id = request.query_params.get('id')
        file_obj = models.Contract.objects.filter(id=file_id).first()
        if file_obj:
            # 拿到文件在数据库中存储的位置
            media_file = str(file_obj.file)
            # 拼接文件路径
            filepath = os.path.join(settings.MEDIA_ROOT, media_file)
            # 拿到文件的名字（该名字包含了文件的格式）
            filename = media_file.split(r'/')[-1]
            file = open(filepath, 'rb')
            response = FileResponse(file)  # 生成文件对象application/msword  application/octet-stream
            response['Content-Type'] = 'application/octet-stream'
            # name.split('.')[0] + '.docx'，
            name = filename
            response['Content-Disposition'] = 'attachment;filename ="%s"' % (
                name.encode('utf-8').decode('ISO-8859-1'))
            return response
        return ApiResponse(code=500,msg='get')
#会议申请的审核
class CheckConferenceView(GenericViewSet,ListModelMixin,UpdateModelMixin):
    serializer_class = serializers.ShowApplyConferenceserializer
    queryset = models.ApllyConference.objects.filter(is_delete=False)
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        #拿到要查看的不同审核情况的申请
        condition = request.query_params.get('condition')
        queryset =models.ApllyConference.objects.filter(is_delete=False,checker__manager_id=request.auth.get('id'),position=condition).order_by('-id')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(data=serializer.data,code=100)
    def update(self, request, *args, **kwargs):
        try:
            id = request.query_params.get('id')
            type = int(request.query_params.get('type'))
            evection = models.ApllyConference.objects.get(id=id)
        except:
            return ApiResponse(code=404,error='无此数据')
        if type:
            #审核不通过、condition改成3，将原因写入
            evection.position=3
            evection.result=request.data.get('result')
            evection.save()
            return ApiResponse(code=100)
        else:
            #审核通过
            evection.position=2
            evection.save()
            return ApiResponse(code=100)

class AddressListView(GenericViewSet,ListModelMixin):
    queryset = models.User.objects
    serializer_class = serializers.AddressListSerializer
    def list(self, request, *args, **kwargs):
        try:
            part = models.Part.objects.get(id=request.query_params.get('part'))
        except:
            part = models.User.objects.get(id=request.auth.get('id')).part_f

        user = models.User.objects.filter(part_f=part)
        ser = serializers.AddressListSerializer(instance=user,many=True)
        return ApiResponse(data=ser.data)

#创建项目任务、展示项目任务
class TaskView(GenericViewSet,CreateModelMixin,ListModelMixin,DestroyModelMixin,UpdateModelMixin):
    serializer_class = serializers.TaskListSerializer
    queryset = models.Task.objects
    # permission_classes = [permiss.PartAdminPermission]
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        stype = request.query_params.get('type')
        condition = request.query_params.get('condition')
        #拿到当前登录的用户
        user = models.User.objects.get(id=request.auth.get('id'))
        #拿到登录用户对应的部门，可以获取到部门的经理id
        part = models.Part.objects.get(id=user.part_f_id)
        if stype == '1':
            queryset =models.Task.objects.filter(Q(manage_id=part.id),is_delete=False,is_end=int(condition))
        else:
            queryset = models.Task.objects.filter(is_delete=False,is_end=False,manage_id=part.id)
        page = self.paginate_queryset(queryset)

        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)
    def create(self, request, *args, **kwargs):
        file=request.FILES.get('file')
        request.data['file']=file
        manage = request.auth.get('id')
        part = models.Part.objects.get(manager_id=manage)
        request.data['manage']=part.id
        ser = serializers.TaskPartserializer(data=request.data)
        if ser.is_valid():
            return ApiResponse()
        return ApiResponse(code=500,error=str(ser.errors))
    def destroy(self, request, *args, **kwargs):
        id = request.query_params.get('id')
        try:
            models.Task.objects.filter(id=id).update(is_delete=True)
            return ApiResponse(code=100)
        except:
            return ApiResponse(code=500,error='无法删除此数据')
    #项目任务，设置状态为完成状态
    def update(self, request, *args, **kwargs):
        task_id= request.query_params.get('id')
        try:
            models.Task.objects.filter(id=task_id).update(is_end=True)
        except Exception as e:
            return ApiResponse(code=500,error=str(e))
        return ApiResponse()
#下载项目文件
class DownloadTaskFileView(GenericAPIView):
    def get(self,request):
        file_id = request.query_params.get('id')
        file_obj = models.Task.objects.filter(id=file_id).first()
        if file_obj:
            # 拿到文件在数据库中存储的位置
            media_file = str(file_obj.file)
            # 拼接文件路径
            filepath = os.path.join(settings.MEDIA_ROOT, media_file)
            # 拿到文件的名字（该名字包含了文件的格式）
            filename = media_file.split(r'/')[-1]
            file = open(filepath, 'rb')
            response = FileResponse(file)  # 生成文件对象application/msword  application/octet-stream
            response['Content-Type'] = 'application/octet-stream'
            # name.split('.')[0] + '.docx'，
            name = filename
            response['Content-Disposition'] = 'attachment;filename ="%s"' % (
                name.encode('utf-8').decode('ISO-8859-1'))
            return response
        return ApiResponse(code=500,msg='get')
#创建项目完成情况
class TaskDetailView(GenericViewSet,ListModelMixin,CreateModelMixin):
    queryset = models.TaskDetail
    serializer_class = serializers
    def list(self, request, *args, **kwargs):
        return ApiResponse(msg='list')
    def create(self, request, *args, **kwargs):
        task_id=request.query_params.get('task_id')
        content = request.data.get('content')
        try:
            #员工对项目的贡献情况
            taskdetail = models.TaskDetail.objects.create(staff_id=request.auth.get('id'),content=content)
            #在第三张表上，写号任务与员工贡献的关系
            models.TaskToDetail.objects.create(staff=taskdetail,task_id=task_id)
            return ApiResponse()
        except Exception as e:
            return ApiResponse(code=500,error=str(e))

#显示项目完成情况，每个人对该项目的贡献次数
class TaskToDetailView(GenericViewSet,ListModelMixin):
    queryset = models.TaskToDetail.objects
    serializer_class = serializers.TaskToDetailSeralizer
    def list(self, request, *args, **kwargs):
        task_id=request.query_params.get('task_id')
        tasktodetail = models.TaskToDetail.objects.filter(task_id=task_id)
        tasktodetail_ser = serializers.TaskToDetailSeralizer(instance=tasktodetail,many=True)
        lis=[]
        for detail in tasktodetail_ser.data:
            taskdetail=models.TaskDetail.objects.get(id=detail.get('staff'))
            ser = serializers.TaskDetailSeralizer(instance=taskdetail)
            lis.append(ser.data)
        return ApiResponse(data=lis)
#获取等级
class LevelForTaskView(GenericViewSet,ListModelMixin):
    queryset = models.Level
    serializer_class = serializers.LevelSeralizer
    def list(self, request, *args, **kwargs):
        queryset = models.Level.objects.all()
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(data=serializer.data)
#拿到当前登录用户所在部门的所有员工信息
class StaffForTaskView(GenericViewSet,ListModelMixin):
    queryset = models.User.objects
    serializer_class = serializers.StaffForTaskSerializer
    def list(self, request, *args, **kwargs):
        #拿到当前用户所在的部门，找到该部门的所有员工
        user = models.User.objects.get(id=request.auth.get('id'))
        part = user.part_f
        queryset = models.User.objects.filter(part_f=part)
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(data=serializer.data)
#员工个人任务的创建和展示
class PersonTaskView(GenericViewSet,ListModelMixin,CreateModelMixin,DestroyModelMixin,UpdateModelMixin):
    queryset = models.StaffTask.objects
    serializer_class = serializers.ListPersonTaskSerializer
    pagination_class = PageNumberEvectionPaginations
    #给部门经理查看的
    def list(self, request, *args, **kwargs):
        user_id = request.auth.get('id')
        is_end = request.query_params.get('is_end')
        part = models.Part.objects.get(manager_id=user_id)

        if is_end=='0':
            #返回没有完成的任务
            queryset = models.StaffTask.objects.filter(Q(apllier_id=part.id),is_end=False,is_del=False).order_by('-create')
        else:
            #返回已经完成的任务
            queryset = models.StaffTask.objects.filter(Q(apllier_id=part.id),is_end=True, is_del=False).order_by('-create')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(data=serializer.data)
    def create(self, request, *args, **kwargs):
        part = models.Part.objects.get(manager_id=request.auth.get('id'))
        request.data['apllier']=part.id
        ser = serializers.PersonTaskSerializer(data=request.data)
        file = request.FILES.get('file')#拿到文件对象
        request.data['file']=file#将文件对象放到request.data中
        if ser.is_valid():
            return ApiResponse()
        return ApiResponse(code=500,error=ser.errors)
    def destroy(self, request, *args, **kwargs):
        task_id = request.query_params.get('task_id')
        try:
            models.StaffTask.objects.filter(id=task_id).update(is_del=True)
        except Exception as e:
            return ApiResponse(code=500,error=str(e))
        return ApiResponse()
    def update(self, request, *args, **kwargs):
        #设置员工任务是完成状态
        task_id =request.query_params.get('task_id')
        try:
            models.StaffTask.objects.filter(id=task_id).update(is_end=True)
        except Exception as e:
            return ApiResponse(code=500,error=str(e))
        return ApiResponse()
class DownloadPersonTaskFileView(GenericAPIView):
    def get(self,request):
        file_id = request.query_params.get('id')
        file_obj = models.StaffTask.objects.filter(id=file_id).first()
        if file_obj:
            # 拿到文件在数据库中存储的位置
            media_file = str(file_obj.file)
            # 拼接文件路径
            filepath = os.path.join(settings.MEDIA_ROOT, media_file)
            # 拿到文件的名字（该名字包含了文件的格式）
            filename = media_file.split(r'/')[-1]
            file = open(filepath, 'rb')
            response = FileResponse(file)  # 生成文件对象application/msword  application/octet-stream
            response['Content-Type'] = 'application/octet-stream'
            # name.split('.')[0] + '.docx'，
            name = filename
            response['Content-Disposition'] = 'attachment;filename ="%s"' % (
                name.encode('utf-8').decode('ISO-8859-1'))
            return response
        return ApiResponse(code=500,msg='get')

class StaffPersonTaskView(GenericViewSet,ListModelMixin):
    queryset = models.StaffTask.objects
    serializer_class = serializers.ListPersonTaskSerializer
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        user_id = request.auth.get('id')
        is_end = request.query_params.get('is_end')
        if is_end == '0':
            # 返回没有完成的任务
            queryset = models.StaffTask.objects.filter(recever_id=user_id, is_end=False,is_del=False).order_by('-create')
        else:
            # 返回已经完成的任务
            queryset = models.StaffTask.objects.filter(recever_id=user_id,is_end=True,is_del=False).order_by('-create')
        print(queryset,'0009090')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)

        return ApiResponse(data=serializer.data)

#员工个人任务详细展示、
class PersonTaskDetailView(GenericViewSet,ListModelMixin,CreateModelMixin):
    queryset = models.TaskStep.objects
    serializer_class = serializers.PersonTaskDetailSerializer
    def list(self, request, *args, **kwargs):
        id = request.query_params.get('task_id')
        detail = self.queryset.filter(stafftask_id=id)
        ser = self.serializer_class(instance=detail,many=True)
        return ApiResponse(msg='list',data=ser.data)
    def create(self, request, *args, **kwargs):
        ser = serializers.TaskStepSerializer(data=request.data)
        if ser.is_valid():
            return ApiResponse()
        return ApiResponse(code=500, error=ser.errors)
class SalaryPartUser(GenericViewSet,ListModelMixin,CreateModelMixin):
    serializer_class = serializers.ShowUserSerializer
    queryset = models.User.objects
    permission_classes = [permiss.PartAdminPermission,]
    pagination_class = PageNumberEvectionPaginations
    def list(self, request, *args, **kwargs):
        # #在路由中拿到部门id，通过部门id，展示对应的员工信息。
        # part_id = request.query_params.filter
        queryset = self.queryset.filter(is_show=True,is_active=True).order_by('part_f')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(data=serializer.data)
    def create(self, request, *args, **kwargs):
        return ApiResponse(msg='create')
#财务部经理上传修改员工的工资
class SalaryForPart(GenericViewSet,RetrieveModelMixin,CreateModelMixin):
    def retrieve(self, request, *args, **kwargs):
        #拿到用户的id，找到员工的最新的工资情况
        user_id = request.query_params.get('user_id')
        salary = models.Salary.objects.filter(users_id=user_id).order_by('-create_time').first()
        ser = serializers.OneSalaryViewSerializer(instance=salary)
        return ApiResponse(msg='get_one',data=ser.data)
    def create(self, request, *args, **kwargs):
        y = time.localtime().tm_year
        m = time.localtime().tm_mon
        d = time.localtime().tm_mday
        m_time = f'{y}-{m - 1}-{d}'
        request.data['m_time']=m_time
        #创建员工的工资
        ser = serializers.OneSalaryViewSerializer(data=request.data) #把工资id传递给序列化器，通过id来判断是新增加数据，还是修改数据
        if ser.is_valid():
            return ApiResponse(msg='create')
        else:
            return ApiResponse(code=500,error=ser.errors)
#员工工资查看
class StaffSalaryView(GenericViewSet,ListModelMixin):
    serializer_class = serializers.StaffSalaryViewSerializer
    queryset = models.Salary.objects
    pagination_class = SalaryPagenation
    #进入工资界面，先展示最新三个月的工资情况
    def list(self, request, *args, **kwargs):
        user = request.auth.get('id')
        queryset = self.queryset.filter(users_id=user).order_by('-m_time')[:3]
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(msg='list',data=serializer.data,set=1)
    #员工通过搜索框，搜索对应年份内的所有工资
    def search(self,request):
        year = request.data.get('year')
        year = str(int(str(year).split('-')[0] )+1)
        user = request.auth.get('id')
        queryset = self.queryset.filter(users_id=user,m_time__year=year).order_by('-m_time')
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(serializer.data)

#签到相关的类
class StaffSignIn(GenericViewSet,RetrieveModelMixin,CreateModelMixin,UpdateModelMixin):
    def retrieve(self, request, *args, **kwargs):
        sign = request.query_params.get('sign')
        user_id = request.auth.get('id')
        currunt = request.query_params.get('currunt')
        year = currunt.split('-',1)[0]
        mont = currunt.split('-')[1]
        day = currunt.rsplit('-')[-1].split(' ')[0]
        new_hour = int(currunt.split(':')[0].split(' ')[-1])  # 签到时
        new_min = int(currunt.split(':')[1])  # 签到分
        if sign=='1' or sign==1:#说明时点击了进行签到按钮
            obj = models.Attendance.objects.filter(user_id=user_id,startime__year=year,startime__month=mont,startime__day=day)
            if obj:
                return ApiResponse(code=200,msg='员工已经签到过了')
            else:
                sign_time = models.SignTime.objects.get(the_type=True)
                is_delay = False
                sign_hour = sign_time.hour #规定签到时
                sign_min = sign_time.min #规定签到分
                if new_hour>sign_hour:#说明迟到了
                    is_delay=True
                elif new_hour==sign_hour:
                    if new_min > sign_min+5:
                        is_delay=True #签到时间，比规定时间晚5分钟就是迟到
                #没有签到，就进行签到
                models.Attendance.objects.create(user_id=user_id,startime=currunt,is_delay=is_delay)
                #签到成功后，就需要记录上班天数
                mon_obj = models.MonthOfStaffSign.objects.filter(staff_id=user_id,month__year=year,month__month=mont)
                if is_delay:
                    delay = 1
                else:
                    delay = 0
                if mon_obj:
                    #当前月已经存在该记录了
                    mon_obj.update(delay_count=F('delay_count')+delay,word_days=F('word_days')+1)

                else:
                    models.MonthOfStaffSign.objects.create(staff_id=user_id,month=f'{year}-{mont}-{day}',word_days=1,delay_count=delay)

                return ApiResponse(code=100,msg='签到成功')
        elif sign=='0' or sign==0:
            #签退逻辑
            out_time = models.SignTime.objects.get(the_type=False)
            out_hour = out_time.hour
            out_min = out_time.min
            if new_hour<out_hour:
                #无法签退
                return ApiResponse(code=400,msg='早退')
            elif new_hour==out_hour and new_min < out_min:
                return ApiResponse(code=400,msg='早退')
            else:
                try:
                    #有记录
                    obj = models.Attendance.objects.get(user_id=user_id,startime__year=year,startime__month=mont,startime__day=day)
                    obj.endtime=currunt
                    sign_hour = obj.startime.hour
                    #上班时长
                    obj.long_time = new_hour-sign_hour-1#默认中文休息1小时
                    obj.save()
                    mon_obj = models.MonthOfStaffSign.objects.filter(staff_id=user_id, month__year=year,month__month=mont)
                    if mon_obj:#有这个月的记录
                        if obj:#早上已经签到了
                            #上班天数就不加一了,因为不能早退，
                            pass
                        else:
                            mon_obj.update(word_days=F('word_days')+1,before_count=F('before_count')+1)
                    else:#当前月份没有记录
                        if obj:
                            pass
                        else:#今天早上没有签到记录，说明迟到了
                            models.MonthOfStaffSign.objects.create(staff_id=user_id,word_days=1,delay_count=1)
                    return ApiResponse(code=100,msg='正常签退')
                except:
                    try:
                        obj = models.Attendance.objects.get(user_id=user_id,endtime__day=day,endtime__year=year,endtime__month=mont)
                        obj.endtime=currunt
                        obj.startime=currunt
                        obj.is_delay=True
                        obj.save()
                    except:

                        models.Attendance.objects.create(is_delay=True,endtime=currunt,startime=currunt,long_time=0)#0代表员工只进行了签退，但没有签到，只能设置为0
                    return ApiResponse(code=500,error='已经签退，但您今天未签到！！')
        else:
            return ApiResponse(code=500,error='无法执行此操作')
    def create(self, request, *args, **kwargs):
        #判断员工今天是否已经签到或签退
        new_time = time.localtime()
        year = new_time.tm_year
        mont = new_time.tm_mon
        day = new_time.tm_mday
        user_id = request.auth.get('id')
        sign_in = models.Attendance.objects.filter(user_id=user_id,startime__year=year,startime__month=mont,startime__day=day)
        sign_out = models.Attendance.objects.filter(user_id=user_id,endtime__year=year,endtime__month=mont,endtime__day=day)
        in_time=0
        out_time=0
        if sign_in:
            in_time = sign_in.first().startime
        if sign_out:
            out_time = sign_out.first().endtime
        dic={'sign_in':sign_in.exists(),'sign_out':sign_out.exists(),'in_time':in_time,'out_time':out_time}
        return ApiResponse(data=dic)
class ShowStaffSign(GenericViewSet,ListModelMixin):
    queryset = models.Attendance.objects
    serializer_class = serializers.ShowStaffSignSerializer
    def list(self, request, *args, **kwargs):
        user_id = request.auth.get('id')
        the_time =  request.query_params.get('the_time',None)
        #用户进入界面时，默认会发起一个请求，默认是给出当前月份的数据
        first = request.query_params.get('flask',None)
        year = time.localtime().tm_year
        month = time.localtime().tm_mon
        send_ym = str(year)+'年'+str(month)
        if first:
            queryset = self.queryset.filter(create__year=year, create__month=month, user_id=user_id).order_by('startime')

        else:
            if the_time:
                search_year = int(the_time.split('-',1)[0])
                search_mont = int(the_time.split('-')[1])
                send_ym =  str(search_year)+'年'+str(search_mont)
            else:
                search_year = time.localtime().tm_year
                search_mont = time.localtime().tm_mon
            queryset = self.queryset.filter(create__year=search_year,create__month=search_mont,user_id=user_id).order_by('startime')
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(data=serializer.data,count=len(serializer.data),month = send_ym)
#修改员工上下班时间
class EditeSignTime(GenericViewSet,RetrieveModelMixin,UpdateModelMixin):
    #获取当前上下班时就
    def retrieve(self, request, *args, **kwargs):
        #签到时间
        signin = models.SignTime.objects.filter(the_type=True).first()
        #签退时间
        signout = models.SignTime.objects.filter(the_type=False).first()
        signin_min = signin.min
        signin_hour = signin.hour
        signout_hour = signout.hour
        signout_min = signout.min
        if signin_min==0:
            signin_min='00'
        if signout_min==0:
            signout_min='00'


        sign_in = str(signin_hour)+':'+str(signin_min)
        sign_out = str(signout_hour)+':'+str(signout_min)
        return ApiResponse(msg='搜索单个',signin=sign_in,signout=sign_out)
    def update(self, request, *args, **kwargs):
        if request.data.get('signin',None):
            signin_hour = request.data.get('signin_hour')
            signin_min = request.data.get('signin_min')
            try:
                models.SignTime.objects.filter(the_type=True).update(hour=signin_hour,min=signin_min)
                return ApiResponse(code=100)
            except:
                return ApiResponse(code=200)
        elif request.data.get('signout',None):
            signout_hour = request.data.get('signout_hour')
            signout_min = request.data.get('signout_min')
            try:
                models.SignTime.objects.filter(the_type=False).update(hour=signout_hour, min=signout_min)
                return ApiResponse(code=100)
            except:
                return ApiResponse(code=200)
        else:
            return ApiResponse(code=500,error='未知错误！！')

#给每月设置应签到次数
class MonthSignCountView(GenericViewSet,ListModelMixin,UpdateModelMixin,CreateModelMixin):
    queryset = models.MonthSignCount.objects
    serializer_class = serializers.MonthSignCountSerializer
    def list(self, request, *args, **kwargs):
        first = request.query_params.get('first',None)
        if first:
            year = time.localtime().tm_year
        else:
            year = request.query_params.get('year')
        queryset = self.queryset.filter(year_month__year=year).order_by('year_month')
        serializer = self.get_serializer(queryset, many=True)
        return ApiResponse(data=serializer.data,year=year)

    def update(self, request, *args, **kwargs):
        row = request.data.get('row')
        try:
            models.MonthSignCount.objects.filter(id=row.get('id')).update(sign_days=row.get('sign_days'))
        except:
            return ApiResponse(code=500,error='修改失败')
        return ApiResponse(code=100,msg='修改成功')
    def create(self, request, *args, **kwargs):
        days = request.data.get('days')
        year_month = request.data.get('year')
        if days and year_month:
            if type(days)==int:
                year = int(year_month.split('-',1)[0])
                month = int(year_month.split('-')[1])
                obj = self.queryset.filter(year_month__year=year,year_month__month=month)
                if obj:
                    return ApiResponse(code=500,error='该月份已经有记录了！！')
                else:
                    self.queryset.create(year_month=year_month,sign_days=days)
                    return ApiResponse(code=100,msg='修改成功')
            else:
                return ApiResponse(code=500,error='输入的天数和月份有问题')
        else:
            return ApiResponse(code=500,error='数据问题')

class TestView(GenericAPIView):
    def get(self, request):
        # mount = []
        # for i in range(1,13):
        #     mount.append(str(i)+'月')
        # level=['WARNING','ERROR']
        # war_lis=[12,23,34,38,23,12,7,20,12,34,12,7]
        # err_lis=[3,5,7,8,6,0,1,2,4,7,2,1]
        # for i in range(12):
        #     models.DetalLogdata.objects.create(mount=mount[i],type=level[0],count=war_lis[i],year_id=2)
        #     models.DetalLogdata.objects.create(mount=mount[i],type=level[0],count=err_lis[i],year_id=2)
        return ApiResponse()
